<template>
	<div>
		<div class="container">
			<div class="handle-box">
				<el-select v-model="query.QueryType" placeholder="查询方式" class="handle-select mr10" @change="SelectTypeChange">
          <el-option key="1" label="用户名" value="username"></el-option>
          <el-option key="2" label="性别" value="gender"></el-option>
					<el-option key="3" label="所在地" value="position"></el-option>
          <el-option key="4" label="职业" value="industry"></el-option>
				</el-select>
        <el-select v-if="query.QueryType==='gender'" v-model="query.SelectGender" placeholder="选择性别" class="handle-select mr10" @change="SelectGenderChange">
          <el-option key="1" label="女" value="0"></el-option>
          <el-option key="2" label="男" value="1"></el-option>
          <el-option key="3" label="保密" value="2"></el-option>
        </el-select>
        <div v-else>
          <el-input v-model="query.SearchInput" placeholder="请输入" class="handle-input mr10"></el-input>
          <el-button type="primary" :icon="Search" @click="handleSearch">搜索</el-button>
        </div>
			</div>

			<el-table
          :data="tableData"
          height="550"
          border class="table" ref="multipleTable" header-cell-class-name="table-header">
				<el-table-column prop="id" label="ID" width="55" align="center"></el-table-column>
				<el-table-column prop="username" label="用户名" align="center"></el-table-column>
        <el-table-column label="性别" align="center">
          <template #default="scope">
              {{ ComputeGender(scope.row.gender) }}
          </template>
        </el-table-column>
				<el-table-column label="头像" align="center">
					<template #default="scope">
						<el-image
							class="table-td-thumb"
              :src="'//images.weserv.nl/?url=150.158.52.191:8080/HeadPortrait/' + scope.row.id + '?t=' + Math.random()"
							:z-index="10"
							:preview-src-list="[scope.row.thumb]"
							preview-teleported
						>
              <template #error>
                <div class="image-slot">
                  <el-image
                      class="table-td-thumb"
                      :src="'//images.weserv.nl/?url=150.158.52.191:8080/HeadPortrait/default?t=' + Math.random()"
                      :z-index="10"
                      :preview-src-list="[scope.row.thumb]"
                      preview-teleported
                  />
                </div>
              </template>
						</el-image>
					</template>
				</el-table-column>
        <el-table-column prop="position" label="地址" align="center">
          <template #default="scope">
            {{ scope.row.position==null?"用户未设置所在地":scope.row.position }}
          </template>
        </el-table-column>
        <el-table-column prop="industry" label="职业" align="center">
          <template #default="scope">
            {{ scope.row.industry==null?"用户未设置职业":scope.row.industry }}
          </template>
        </el-table-column>
				<el-table-column prop="join_time" label="注册时间" align="center"></el-table-column>
				<el-table-column label="操作" width="220" align="center">
					<template #default="scope">
						<el-button text :icon="Edit" @click="handleResetPwd(scope.$index, scope.row)">
							重置密码
						</el-button>
						<el-button text :icon="Delete" class="red" @click="handleDelete(scope.$index, scope.row)">
							注销
						</el-button>
					</template>
				</el-table-column>
			</el-table>
		</div>
	</div>
</template>

<script setup lang="ts" name="basetable">
import {ref, reactive, watch} from 'vue';
import { useRouter } from "vue-router";
import { ElMessage, ElMessageBox } from 'element-plus';
import { Delete, Edit, Search } from '@element-plus/icons-vue';
import axios from "axios";

interface TableItem {
	id: string;
	username: string;
  gender: string;
  email: string;
	position: string;
  join_time: string;
}

const query = reactive({
	QueryType: 'username',
  SelectGender: '',
	SearchInput: '',
	pageIndex: 1,
	pageSize: 10
});
const allData = ref<TableItem[]>([]);
const tableData = ref<TableItem[]>([]);
// 获取表格数据
const getData = () => {
  axios.get(`http://localhost:8080/admin/user`)
      .then(res=>{
        allData.value=res.data.data
        tableData.value=allData.value
      })
};
getData();

// 查询操作
const handleSearch = () => {
  /*let str1="长沙"
  let str2="长沙"
  console.log(str1.toLowerCase().indexOf(str2.toLowerCase()))*/
  if(query.SearchInput==""){
    tableData.value=allData.value
  }else {
    tableData.value = []
    for(let i=0;i<allData.value.length;i++){
      if(allData.value[i][query.QueryType]!=null&&allData.value[i][query.QueryType].toLowerCase().indexOf(query.SearchInput.toLowerCase())!=-1){
        tableData.value.push(allData.value[i])
      }
    }
  }
};
const SelectTypeChange = () => {
  if(query.QueryType==="gender"){
    if(query.SelectGender==="0"||query.SelectGender==="1"){
      tableData.value=[]
      for(let i=0;i<allData.value.length;i++){
        if(allData.value[i].gender==query.SelectGender){
          tableData.value.push(allData.value[i])
        }
      }
    }
  }
};
const SelectGenderChange = () => {
  tableData.value=[]
  for(let i=0;i<allData.value.length;i++){
    if(allData.value[i].gender==query.SelectGender){
      tableData.value.push(allData.value[i])
    }
  }
};
const ComputeGender = (value:string) => {
  if(value=="0"){
    return "女"
  }else if(value=="1"){
    return "男"
  }else{
    return "保密"
  }
};
// 分页导航
const handlePageChange = (val: number) => {
	query.pageIndex = val;
	getData();
};

// 表格编辑时弹窗和保存
const editVisible = ref(false);
let form = reactive({
	name: '',
	address: ''
});

const handleResetPwd = (index: number, row: any) => {
	axios.patch(`http://localhost:8080/admin/`+row.id+`/password`)
      .then(res=>{
        if(res.data.data){
          ElMessage.success('重置密码成功!');
        }else{
          ElMessage.error("重置密码失败!")
        }
      })
};
// 删除操作
const handleDelete = (index: number, row: any) => {
  ElMessageBox.confirm('确定要删除吗?', '提示', {
    type: 'warning'
  })
      .then(() => {
        axios.delete(`http://localhost:8080/user?user_id=`+row.id)
            .then(res=>{
              if(res.data.data){
                ElMessage.success("注销用户成功!")
                let deleteID = tableData.value[index].id
                tableData.value.splice(index,1)
                for(let i=0;i<allData.value.length;i++){
                  if(allData.value[i].id===deleteID){
                    allData.value.splice(i,1)
                    break;
                  }
                }
              }else{
                ElMessage.error("注销用户失败!")
              }
            })
      })
      .catch(() => {});
};
const router = useRouter()
watch(
    () => router.currentRoute.value,
    (newRoute) => {
      if(newRoute.name=="user"){
        getData()
      }
    },
    { immediate: true }
);
</script>

<style scoped>
.handle-box {
  width: auto;
	margin-bottom: 20px;
  display: flex;
  justify-content: left;
}

.handle-select {
	width: 120px;
}

.handle-input {
	width: 300px;
}
.table {
	width: 100%;
	font-size: 14px;
}
.red {
	color: #F56C6C;
}
.mr10 {
	margin-right: 10px;
}
.table-td-thumb {
	display: block;
	margin: auto;
	width: 40px;
	height: 40px;
}
</style>
